package com.kobi.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kobi.data.Book;

import com.kobi.connection.*;


@WebServlet("/quertoneBook")
public class quertoneBook extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs=null;
        Book book=null;
        request.setCharacterEncoding("UTF-8");
        String title=request.getParameter("title");
        try {
            conn = JDBCUtils.getConnection();
            String sql = "select * from books where title=?;";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,title);
            rs= pstmt.executeQuery();
            if(rs.next()) {
                book=new Book();
                book.setBookid(rs.getString(1));
                book.setTitle(rs.getString(2));
                book.setAuthor(rs.getString(3));
                book.setPublisher(rs.getString(4));
                book.setPrice(rs.getDouble(5));
                request.setAttribute("book", book);
                request.getRequestDispatcher("/showone.jsp").forward(request, response);
            }
            else {
            	request.setAttribute("title",title);
            	request.getRequestDispatcher("/losequery.jsp").forward(request, response);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //6. 释放资源
            JDBCUtils.close(rs,pstmt,conn);
        }
	}

}
